package com.kmzx.one.project.config.listener;

import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.kmzx.one.common.constants.Constants;
import com.kmzx.one.common.enums.TradeTypeEnums;
import com.kmzx.one.project.entity.UserOrder;
import com.kmzx.one.project.entity.WxPayOrder;
import com.kmzx.one.project.events.PayOrderEvent;
import com.kmzx.one.project.mapper.CustomerMapper;
import com.kmzx.one.project.mapper.UserInviteMapper;
import com.kmzx.one.project.mapper.UserOrderMapper;
import com.kmzx.one.project.mapper.WarehouseMapper;
import com.kmzx.one.project.mapper.WxPayMapper;
import com.kmzx.one.project.others.dto.WikiH5PayCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;


@Component("payOrderListener")
public class PayOrderListener {

    private static Logger logger = LoggerFactory.getLogger(PayOrderListener.class);

    private static String expirePrefix = "expires_";

    @Autowired
    CustomerMapper customerMapper;

    @Autowired
    UserOrderMapper userOrderMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    UserInviteMapper userInviteMapper;

    @Autowired
    WarehouseMapper warehouseMapper;

    @Autowired
    WxPayMapper wxPayMapper;

    @Async
    @EventListener(classes = {PayOrderEvent.class})
    @Transactional(rollbackFor = Exception.class)
    public void defaultPayOrderEvent(PayOrderEvent payOrderEvent) {
        logger.info("---------------------------");
        logger.info("利用@EventListener注解监听用户支付事件并向用户发送 收益");
        UserOrder order = payOrderEvent.getUserOrder();
        Date updateTime = new Date();
        order.setUpdateTime(updateTime);
        Integer states = order.getStates();
        // todo  交易成功
        if (states == 1) {
            //  todo 更新主订单表
            userOrderMapper.updateByIdSelective(order);
            // todo 更新子订单表
            userOrderMapper.batchUpdateSubOrder(order.getId(), 1, updateTime);
            // todo  更新库存表
            warehouseMapper.successWarehouseDetail(2, updateTime, order.getId());
            stringRedisTemplate.delete(Constants.lifestyleOrderPrefix + order.getId());
            // kinds 1,小程序支付
            // kinds 2,H5 支付
            int kinds = payOrderEvent.getKinds();
            if (kinds == 1) {

                WxPayOrderNotifyResult notifyResult = (WxPayOrderNotifyResult) payOrderEvent.getNotifyResult();
                if (notifyResult != null) {
                    try {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");//注意月份是MM
                        Date date = simpleDateFormat.parse(notifyResult.getTimeEnd());
                        String nonceStr = notifyResult.getNonceStr();
                        WxPayOrder wxPayOrder = wxPayMapper.selectById(nonceStr);
                        wxPayOrder.setSuccess(0).setUpdateTime(updateTime)
                                .setWxResp(payOrderEvent.getPostData());
                        wxPayOrder.setBankType(notifyResult.getBankType())
                                .setCashFee(notifyResult.getCashFee())
                                .setWxTradeNo(notifyResult.getTransactionId())
                                .setTimeEnd(notifyResult.getTimeEnd())
                                .setPayTime(date)
                                .setIsSubscribe(notifyResult.getSubIsSubscribe());
                        wxPayMapper.updateWxPayOrderByIdSel(wxPayOrder);
                        Integer tradeType = order.getTradeType();
                        //
                        if (tradeType == TradeTypeEnums.Sea_Trade.getCode()) {
                            ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
                            opsForValue.set(Constants.push_file_gate + order.getId() + "_" + order.getTradeNum(), order.getId(), 2, TimeUnit.SECONDS);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            } else if (kinds == 2) {
                WikiH5PayCallback notifyResult = (WikiH5PayCallback) payOrderEvent.getNotifyResult();
                if (notifyResult != null) {
                    try {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");//注意月份是MM
                        Date date = simpleDateFormat.parse(notifyResult.getTime_end());
                        String nonceStr = notifyResult.getNonce_str();
                        WxPayOrder wxPayOrder = wxPayMapper.selectById(nonceStr);
                        wxPayOrder.setSuccess(0).setUpdateTime(updateTime)
                                .setWxResp(payOrderEvent.getPostData()).setPayTime(date);
                        wxPayOrder.setBankType(notifyResult.getBank_type())
                                .setCashFee(Integer.valueOf(notifyResult.getCash_fee()))
                                .setWxTradeNo(notifyResult.getTransaction_id())
                                .setTimeEnd(notifyResult.getTime_end())
                                .setIsSubscribe(notifyResult.getIs_subscribe());
                        wxPayMapper.updateWxPayOrderByIdSel(wxPayOrder);
                        Integer tradeType = order.getTradeType();
                        //
                        if (tradeType == TradeTypeEnums.Sea_Trade.getCode()) {
                            ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
                            opsForValue.set(Constants.push_file_gate + order.getId() + "_" + order.getTradeNum(), order.getId(), 2, TimeUnit.SECONDS);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

            }

            int i = userOrderMapper.checkOrderKindsNum(order.getId(), "005");
            if (i > 0) {
                ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
                opsForValue.set(Constants.ning_bo_normal + order.getId() + "_" + order.getId(), order.getId(), 10, TimeUnit.SECONDS);
            }

            ValueOperations<String, String> expandUserOrder = stringRedisTemplate.opsForValue();
            expandUserOrder.set(Constants.expand_user_gate+order.getId(), order.getId(), 20, TimeUnit.SECONDS);


        }

        // todo  交易失败
        if (states == 5) {
            //  todo 更新主订单表
            userOrderMapper.updateByIdSelective(order);
            // todo 更新子订单表
            userOrderMapper.batchUpdateSubOrder(order.getId(), 5, updateTime);
        }

        stringRedisTemplate.delete(expirePrefix + order.getId());
    }


}


